const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const Article = require('../models/Article');
const auth = require('../middleware/auth');

// 获取文章列表
router.get('/', async (req, res) => {
    try {
        const { page = 1, limit = 10, tag, search } = req.query;
        const query = {};

        if (tag) {
            query.tags = tag;
        }

        if (search) {
            query.$or = [
                { title: { $regex: search, $options: 'i' } },
                { content: { $regex: search, $options: 'i' } }
            ];
        }

        const articles = await Article.find(query)
            .populate('author', 'username avatar')
            .sort({ createdAt: -1 })
            .limit(limit * 1)
            .skip((page - 1) * limit);

        const count = await Article.countDocuments(query);

        res.json({
            articles,
            totalPages: Math.ceil(count / limit),
            currentPage: page
        });
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 发布文章
router.post('/', auth, [
    body('title').trim().notEmpty().withMessage('标题不能为空'),
    body('content').trim().notEmpty().withMessage('内容不能为空')
], async (req, res) => {
    try {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(400).json({ errors: errors.array() });
        }

        const { title, content, tags } = req.body;
        const article = new Article({
            title,
            content,
            tags: tags || [],
            author: req.user._id
        });

        await article.save();
        res.status(201).json(article);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 删除文章
router.delete('/:id', auth, async (req, res) => {
    try {
        const article = await Article.findById(req.params.id);
        
        if (!article) {
            return res.status(404).json({ message: '文章不存在' });
        }

        if (article.author.toString() !== req.user._id.toString()) {
            return res.status(403).json({ message: '没有权限删除此文章' });
        }

        await article.remove();
        res.json({ message: '文章已删除' });
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取单篇文章
router.get('/:id', async (req, res) => {
    try {
        const article = await Article.findById(req.params.id)
            .populate('author', 'username avatar')
            .populate('comments.user', 'username avatar');

        if (!article) {
            return res.status(404).json({ message: '文章不存在' });
        }

        res.json(article);
    } catch (error) {
        res.status(500).json({ message: '服务器错误' });
    }
});

// 更新文章
router.put('/:id', auth, async (req, res) => {
    try {
        const { title, content, tags } = req.body;
        const article = await Article.findById(req.params.id);

        if (!article) {
            return res.status(404).json({ message: '文章不存在' });
        }

        // 检查是否是文章作者
        if (article.author.toString() !== req.user._id.toString()) {
            return res.status(403).json({ message: '没有权限修改此文章' });
        }

        article.title = title || article.title;
        article.content = content || article.content;
        article.tags = tags || article.tags;

        await article.save();

        res.json({
            message: '文章更新成功',
            article
        });
    } catch (error) {
        res.status(500).json({ message: '服务器内部错误' });
    }
});

module.exports = router; 